//
//  Utilities.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/6/11.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "Utilities.h"
#import "sys/utsname.h"
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
#import <UIKit/UIFeedbackGenerator.h>


#define TT_kInitVector  @"ffGGtsdfzxCv5568"  //偏移量
#define TT_DESKey       @"gg356tt8g5h6j9jh"  //key

static NSMutableDictionary *soundIDs;

@interface Utilities ()

@end
@implementation Utilities

#pragma mark  微信分享压缩图片到32K ------------------------------
+ (UIImage *)TT_compressImageQualityDichotomy:(UIImage *)image toByte:(NSInteger)maxLength
{
    CGFloat compression = 1;
     NSUInteger count = 0;
    maxLength = 32000;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length > maxLength && compression > 0) {
         compression -= 0.05;
         count++;
         // 当压缩到某个阈值的时候，这句代码就没有效果了
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"%@", [NSString stringWithFormat:@"压缩次数：%zd，压缩比例：%f，压缩后的图片大小：%f kb", count, compression, data.length / 1000.0]);
     }
     
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}

+ (NSData *)TT_compressImageQualityDichotomyData:(UIImage *)image toByte:(NSInteger)maxLength
{
    double compression = 1;
     NSUInteger count = 0;
    maxLength = 32000;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length > maxLength && compression > 0) {
         compression = compression - 0.1;
         count++;
         // 当压缩到某个阈值的时候，这句代码就没有效果了
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"%@", [NSString stringWithFormat:@"压缩次数：%zd，压缩比例：%f，压缩后的图片大小：%f kb", count, compression, data.length / 1000.0]);
     }

     return data;
}

#pragma mark  SVProgressHUD 存储临时数据操作 ------------------------------
+ (void)setToNSUserDefaults:(NSString *)key value:(NSString *)value{
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)getFromNSUserDefaults:(NSString *)key{
    
    NSString *value = [[NSUserDefaults standardUserDefaults] valueForKey:key];
    return value;
}


#pragma 震动反馈
+ (void)tapticEngineWork {
    
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator * impactLight = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [impactLight impactOccurred];
        
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark 检查是否设置了网络代理
+ (BOOL)getProxyStatus {
    NSDictionary *proxySettings =  (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = [proxies objectAtIndex:0];
    
//    NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]);
//    NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
//    NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]);
    
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]){
        //没有设置代理
        return NO;
    }else{
        //设置代理了
        return YES;
    }
}

#pragma mark 获取当前时间戳 秒为单位
+(NSTimeInterval )getCurrentTimestamp {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

    [formatter setDateStyle:NSDateFormatterMediumStyle];

    [formatter setTimeStyle:NSDateFormatterShortStyle];

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    //设置时区,这个对于时间的处理有时很重要

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];

    [formatter setTimeZone:timeZone];

    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

    NSTimeInterval timeSp = (NSInteger)([datenow timeIntervalSince1970]*1000);
//    timeSp = timeSp*1000;
//    timeSp = (NSInteger)(timeSp/1000);
    
    return timeSp;
}

+(NSDate *)getDateWithTimestamp:(NSTimeInterval)timestamp {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *datestr = [dateFormatter dateFromString:[Utilities getTimeFromTimestamp:timestamp]];
    return datestr;
}

+(NSString *)compareMaxDateStr:(NSString *)date1 withDateStr:(NSString *)date2 {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date1str = [formatter dateFromString:date1];
    NSDate *date2str = [formatter dateFromString:date2];

    NSTimeInterval time1 = [Utilities getTimestampWithDate:date1str];
    NSTimeInterval time2 = [Utilities getTimestampWithDate:date2str];

    if (time1 > time2) {
        return date1;
    } else if (time1 == time2) {
        return date1;
    }else{
        return date2;
    }
}

+(NSString *)compareMinDateStr:(NSString *)date1 withDateStr:(NSString *)date2 {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date1str = [formatter dateFromString:date1];
    NSDate *date2str = [formatter dateFromString:date2];

    NSTimeInterval time1 = [Utilities getTimestampWithDate:date1str];
    NSTimeInterval time2 = [Utilities getTimestampWithDate:date2str];

    if (time1 > time2) {
        return date2;
    } else if (time1 == time2) {
        return date2;
    }else{
        return date1;
    }
}

+(NSDate *)compareMinDate:(NSDate *)date1 withDateStr:(NSDate *)date2 {

    NSTimeInterval time1 = [Utilities getTimestampWithDate:date1];
    NSTimeInterval time2 = [Utilities getTimestampWithDate:date2];

    if (time1 > time2) {
        return date2;
    } else if (time1 == time2) {
        return date2;
    }else{
        return date1;
    }
}

// 服务器当前时间戳（精确到毫秒）
+ (NSTimeInterval)getCurrentServerTimestamp{
    // 最后保存的服务器时间戳
    NSTimeInterval lastSaveServerTimeStamp = (NSInteger)[[NSUserDefaults standardUserDefaults] doubleForKey:@"kLastSaveServerTimeStamp"];
    
    
    // 最后保存服务器时间戳时的本地时间戳
    NSTimeInterval lastSaveLocalTimeStamp = (NSInteger)[[NSUserDefaults standardUserDefaults] doubleForKey:@"kLastSaveLocalTimeStamp"];
    // 当前本地时间戳
    NSTimeInterval currentLocalTimeStamp = (NSInteger)([[NSDate date] timeIntervalSince1970]*1000);

    if (lastSaveLocalTimeStamp != 0 || lastSaveServerTimeStamp != 0) {
        return lastSaveServerTimeStamp + (currentLocalTimeStamp - lastSaveLocalTimeStamp);
    }else{
        // 如果没有获取到服务器时间，说明客户端还没开始用过，则视服务器时间与本地时间相同
        

        return  currentLocalTimeStamp;
    }
}

+ (NSTimeInterval )getTimestampWithDate:(NSDate *)date {
    NSTimeInterval timeSp = (double)([date timeIntervalSince1970]*1000);
    return timeSp;
}

////检查是否包含小数位
//+ (BOOL)isDoubleValueContainDecimal:(double)doubleValue {
//    if (doubleValue - floor(doubleValue) < 0.01) {
//        return NO;
//    } else {
//        return YES;
//    }
//}

#pragma mark ---- 将时间戳转换成时间
+ (NSString *)getTimeFromTimestamp:(NSTimeInterval)time {
    //将对象类型的时间转换为NSDate类型
    time = time/1000;
    NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:time];
    //设置时间格式
    NSDateFormatter * formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //将时间转换为字符串
    NSString *timeStr=[formatter stringFromDate:myDate];
    return timeStr;
}

+ (NSString *)getTimeFromTimestamp:(NSTimeInterval)time AndFormater:(NSDateFormatter *)formatter{
    //将对象类型的时间转换为NSDate类型
    time = time/1000;
    NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:time];
    //设置时间格式
    //将时间转换为字符串
    NSString *timeStr=[formatter stringFromDate:myDate];
    return timeStr;
}


+ (NSString *)disable_emoji:(NSString *)text {

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@"*"];
    return modifiedString;
}

+ (BOOL)isSameDay:(NSTimeInterval)iTime1 Time2:(NSTimeInterval)iTime2 {
    //传入时间毫秒数
    NSDate *pDate1 = [NSDate dateWithTimeIntervalSince1970:iTime1/1000];
    NSDate *pDate2 = [NSDate dateWithTimeIntervalSince1970:iTime2/1000];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:pDate1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:pDate2];
    
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}

+ (BOOL)isBetweenFromHour:(NSInteger)fromHour toHour:(NSInteger)toHour {
    NSDate *dateFrom = [Utilities getCustomDateWithHour:fromHour];
    NSDate *dateTo = [Utilities getCustomDateWithHour:toHour];
    NSDate *currentDate = [NSDate date];
    if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending){
        NSLog(@"该时间在 %ld:00-%ld:00 之间！", (long)fromHour, (long)toHour);
        return YES;
    }else{
        NSLog(@"不在该时间段 %ld:00-%ld:00 之间！", (long)fromHour, (long)toHour);
        return NO;
    }
}
 
+ (NSDate *)getCustomDateWithHour:(NSInteger)hour{
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
    //设置当天的某个点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return [resultCalendar dateFromComponents:resultComps];
}


+ (NSString *)getTodayAfterDateWithCount:(NSInteger)count {
    NSDate *currentDate = [NSDate date];
    
    NSDate *appointDate;    // 指定日期声明
    NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
    appointDate = [currentDate initWithTimeIntervalSinceNow: oneDay * count];
    
    NSDateFormatter * formatter=[[NSDateFormatter alloc] init];
//    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
//    [formatter setTimeZone:timeZone];

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //将时间转换为字符串
    NSString *timeStr=[formatter stringFromDate:appointDate];
    return timeStr;
}

+ (NSString *)changeDoubleToString:(double)doubleValue{
    NSString *doubleStr = [NSString stringWithFormat:@"%f",doubleValue];
    NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithString:doubleStr];
    return dn.stringValue;
}

+ (NSString *)getDeviceIdentifier {
    // 需要#import "sys/utsname.h"
    struct utsname systemInfo;
    uname(&systemInfo);
    // 获取设备标识Identifier
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    // iPhone
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone10,1"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    if ([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    if ([platform isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if ([platform isEqualToString:@"iPhone11,6"]) return @"iPhone XS MAX";
    if ([platform isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([platform isEqualToString:@"iPhone12,1"]) return @"iPhone 11";
    if ([platform isEqualToString:@"iPhone12,3"]) return @"iPhone 11 Pro";
    if ([platform isEqualToString:@"iPhone12,5"]) return @"iPhone 11 Pro Max";
    if ([platform isEqualToString:@"iPhone12,8"]) return @"iPhone SE (2nd generation)";
    if ([platform isEqualToString:@"iPhone13,1"]) return @"iPhone 12 mini";
    if ([platform isEqualToString:@"iPhone13,2"]) return @"iPhone 12";
    if ([platform isEqualToString:@"iPhone13,3"]) return @"iPhone 12 Pro";
    if ([platform isEqualToString:@"iPhone13,4"]) return @"iPhone 12 Pro Max";
    
    
    // iPod
    if ([platform isEqualToString:@"iPod1,1"])  return @"iPod Touch 1";
    if ([platform isEqualToString:@"iPod2,1"])  return @"iPod Touch 2";
    if ([platform isEqualToString:@"iPod3,1"])  return @"iPod Touch 3";
    if ([platform isEqualToString:@"iPod4,1"])  return @"iPod Touch 4";
    if ([platform isEqualToString:@"iPod5,1"])  return @"iPod Touch 5";
    if ([platform isEqualToString:@"iPod7,1"])  return @"iPod Touch 6";
    if ([platform isEqualToString:@"iPod9,1"])  return @"iPod Touch 7";
    
    // iPad
    if ([platform isEqualToString:@"iPad1,1"])  return @"iPad 1";
    if ([platform isEqualToString:@"iPad2,1"])  return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])  return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,4"])  return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,5"])  return @"iPad Mini 1";
    if ([platform isEqualToString:@"iPad2,6"])  return @"iPad Mini 1";
    if ([platform isEqualToString:@"iPad2,7"])  return @"iPad Mini 1";
    if ([platform isEqualToString:@"iPad3,1"])  return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,2"])  return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,3"])  return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])  return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,5"])  return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])  return @"iPad 4";
    if ([platform isEqualToString:@"iPad4,1"])  return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,2"])  return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,3"])  return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,4"])  return @"iPad Mini 2";
    if ([platform isEqualToString:@"iPad4,5"])  return @"iPad Mini 2";
    if ([platform isEqualToString:@"iPad4,6"])  return @"iPad Mini 2";
    if ([platform isEqualToString:@"iPad4,7"])  return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad4,8"])  return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad4,8"])  return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad4,9"])  return @"iPad mini 4";
    if ([platform isEqualToString:@"iPad5,2"])  return @"iPad mini 4";
    if ([platform isEqualToString:@"iPad5,3"])  return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad5,4"])  return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad6,3"])  return @"iPad Pro (9.7-inch)";
    if ([platform isEqualToString:@"iPad6,4"])  return @"iPad Pro (9.7-inch)";
    if ([platform isEqualToString:@"iPad6,7"])  return @"iPad Pro (12.9-inch)";
    if ([platform isEqualToString:@"iPad6,8"])  return @"iPad Pro (12.9-inch)";
    if ([platform isEqualToString:@"iPad6,11"])  return @"iPad 5";
    if ([platform isEqualToString:@"iPad6,12"])  return @"iPad 5";
    if ([platform isEqualToString:@"iPad7,1"])  return @"iPad Pro 2(12.9-inch)";
    if ([platform isEqualToString:@"iPad7,2"])  return @"iPad Pro 2(12.9-inch)";
    if ([platform isEqualToString:@"iPad7,3"])  return @"iPad Pro (10.5-inch)";
    if ([platform isEqualToString:@"iPad7,4"])  return @"iPad Pro (10.5-inch)";
    if ([platform isEqualToString:@"iPad7,5"])  return @"iPad 6";
    if ([platform isEqualToString:@"iPad7,6"])  return @"iPad 6";
    if ([platform isEqualToString:@"iPad7,11"])  return @"iPad 7";
    if ([platform isEqualToString:@"iPad7,12"])  return @"iPad 7";
    if ([platform isEqualToString:@"iPad8,1"])  return @"iPad Pro (11-inch) ";
    if ([platform isEqualToString:@"iPad8,2"])  return @"iPad Pro (11-inch) ";
    if ([platform isEqualToString:@"iPad8,3"])  return @"iPad Pro (11-inch) ";
    if ([platform isEqualToString:@"iPad8,4"])  return @"iPad Pro (11-inch) ";
    if ([platform isEqualToString:@"iPad8,5"])  return @"iPad Pro 3 (12.9-inch) ";
    if ([platform isEqualToString:@"iPad8,6"])  return @"iPad Pro 3 (12.9-inch) ";
    if ([platform isEqualToString:@"iPad8,7"])  return @"iPad Pro 3 (12.9-inch) ";
    if ([platform isEqualToString:@"iPad8,8"])  return @"iPad Pro 3 (12.9-inch) ";
    if ([platform isEqualToString:@"iPad11,1"])  return @"iPad mini 5";
    if ([platform isEqualToString:@"iPad11,2"])  return @"iPad mini 5";
    if ([platform isEqualToString:@"iPad11,3"])  return @"iPad Air 3";
    if ([platform isEqualToString:@"iPad11,4"])  return @"iPad Air 3";
    
    // 其他
    if ([platform isEqualToString:@"i386"])   return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])  return @"iPhone Simulator";
    
    return platform;
}

#pragma mark 检查是否是手机号
+ (BOOL)checkPhoneTel:(NSString *)phoneStr
{
    if (phoneStr && phoneStr.length) {
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"1+[3456789]+\\d{9}"];
        BOOL isMatch = [pred evaluateWithObject:phoneStr];
        return isMatch;
    }
    return NO;
}

#pragma mark 拨打电话
+ (void)callPhone:(NSString*)phoneNum {
    
    if(phoneNum.length==0){
        return;
    }

    NSString *callPhone = [NSString stringWithFormat:@"tel:%@", phoneNum];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:^(BOOL success) {
        
    }];

    
}

+ (NSString *)base64EncodeString:(NSString *)str {
    //1、先转换成二进制数据
    NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding];
    //2、对二进制数据进行base64编码，完成后返回字符串
    return [data base64EncodedStringWithOptions:0];
}

#pragma mark DES 加密
+ (NSString *)encodeDesWithString:(NSString *)str{
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    size_t plainTextBufferSize = [data length];
    const void *vplainText = (const void *)[data bytes];
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [TT_DESKey UTF8String];            //key
    const void *vinitVec = (const void *) [TT_kInitVector UTF8String];   //偏移量
    
    /*
     在JAVA中："DES/CBC/PKCS5Padding"  对应的  Object-C的是 kCCOptionPKCS7Padding.
               "DES/ECB/PKCS5Padding" 对应的   Object-C的是   kCCOptionPKCS7Padding | kCCOptionECBMod
     */
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithmDES,
                       kCCOptionPKCS7Padding,  //对齐方式
                       vkey,
                       kCCKeySizeDES,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes
                       );
    
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
    NSString *result = [myData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return result;
    
}

#pragma mark DES 解密
+ (NSString *)decodeDesWithString:(NSString *)str{
    NSData *encryptData = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    size_t plainTextBufferSize = [encryptData length];
    const void *vplainText = [encryptData bytes];
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [TT_DESKey UTF8String];
    const void *vinitVec = (const void *) [TT_kInitVector UTF8String];
    
    /*
     在JAVA中："DES/CBC/PKCS5Padding"  对应的  Object-C的是   kCCOptionPKCS7Padding.
              "DES/ECB/PKCS5Padding" 对应的   Object-C的是   kCCOptionPKCS7Padding | kCCOptionECBMod
     */
    ccStatus = CCCrypt(kCCDecrypt,
                       kCCAlgorithmDES,
                       kCCOptionPKCS7Padding,  //对齐方式
                       vkey,
                       kCCKeySizeDES,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes
                       );
    NSString *result = [[NSString alloc]
                        initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                    length:(NSUInteger)movedBytes]
                        encoding:NSUTF8StringEncoding];
    
    return result;
}

#pragma mark MD5
+ (NSString *)md5:(NSString *)string {
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%2X", digest[i]];
    }
    return result;
}

#pragma mark NeteaseMd5 云信密码Md5
+ (NSString *)NeteaseMd5:(NSString *)string {
    const char *cstr = [string UTF8String];
    unsigned char result[16];
    CC_MD5(cstr, (CC_LONG)strlen(cstr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


#pragma mark 计算string宽度
+ (float)getStringWidthWithString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height{

    CGSize size = [value boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:fontSize]} context:nil].size;

    return size.width;
}

+ (NSString *)fixHtmlStringWithUrlArray:(NSArray *)array text:(NSString *)str {
    
    NSString *arrayString = @"";
    NSString *htmlString = @"";
    
    NSString *text = [NSString stringWithFormat:@"<p>%@</p>",str];
    for (int i = 0; i < array.count; i++) {
        NSString *picItem = [NSString stringWithFormat:@"<img class='packageDetail_content_tabs_img' src='%@' />",array[i]];
        arrayString = [NSString stringWithFormat:@"%@%@",arrayString,picItem];
    }
    htmlString = [NSString stringWithFormat:@"<p>%@</p><p>%@</p>",text,arrayString];
    return htmlString;
}

+ (CGFloat)getStringHeightWithText:(NSString *)text font:(UIFont *)font viewWidth:(CGFloat)width {
    // 设置文字属性 要和label的一致
    NSDictionary *attrs = @{NSFontAttributeName :font};
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    // 计算文字占据的宽高
    CGSize size = [text boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    // 当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.height);
}

+ (CGFloat)getStringHeightWithText:(NSString *)text lineSpace:(CGFloat)lineSpace fontName:(UIFont *)fontName viewWidth:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineSpacing = lineSpace;
    NSDictionary *dic = @{NSFontAttributeName:fontName, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@0.1f};
    CGSize size = [text boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

#pragma mark 计算高度
+ (CGFloat )calculateLabelHeightWithText:(NSString *)text lineSpace:(NSInteger )lineSpace fontName:(UIFont *)fontName size:(CGSize )size label:(UILabel *)label {
    CGFloat height = 0;
    if (text.length > 0) {
        // 计算内容高度,判断显示几行
        NSString *firstWord = [text substringToIndex:1];
        CGFloat oneRowHeight = [firstWord sizeWithAttributes:@{NSFontAttributeName:fontName}].height;
        NSDictionary *attributes = @{NSFontAttributeName:fontName};
        CGSize textSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
        CGFloat rows = textSize.height / oneRowHeight;
        if (rows == 1) {
            lineSpace = 0;
            height = oneRowHeight;
        } else if (rows > 1) {
            height = (oneRowHeight + lineSpace) * rows;
        }
        
    }
    return height;
}

+ (NSMutableDictionary *)getParams:(NSString *)str
{
    
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"%@",err);
        return nil;
    }
    return dic.mutableCopy;
    
    

}

+ (NSMutableDictionary *)getUrlParam:(NSString *)str {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSArray *item = [str componentsSeparatedByString:@"&"];
    for (NSString *param in item) {
        NSArray *paramArray = [param componentsSeparatedByString:@"="];

        if (paramArray.count < 2) {
            return @{}.mutableCopy;
        } else if (paramArray.count == 2) {
            [dict setObject:[NSString stringWithFormat:@"%@", paramArray[1]] forKey:paramArray[0]];
        } else if (paramArray.count > 2) {
            //有可能是url带参
            NSArray *escArray = [param componentsSeparatedByString:@"="];
            NSString *escStr = [NSString stringWithFormat:@"%@%@",escArray[0],@"="];
            NSString *url =  [param stringByReplacingOccurrencesOfString:escStr withString:@""];
            [dict setObject:[NSString stringWithFormat:@"%@", url] forKey:escArray[0]];
        }
    }

    return dict;
}

+ (NSDictionary *)convert2DictionaryWithJSONString:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"%@",err);
        return nil;
    }
    return dic;
}

#pragma mark dic转jsonString
+ (NSString *)stringWithDictionary:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}


#pragma mark string转dic
+ (NSDictionary *)dictionaryWithString:(NSString *)jsonString
{
    if (jsonString == nil) {return nil;}
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err){return nil;}
    return dic;
}

#pragma mark json转dic
+ (NSDictionary *)dictionaryWithJsonString:(id)jsonD{
    if (jsonD == nil) {
        return nil;
    }
    
    NSData *jsonData = nil;
    if ([jsonD isKindOfClass:[NSString class]]){
        jsonData = [jsonD dataUsingEncoding:NSUTF8StringEncoding];
    }else if ([jsonD isKindOfClass:[NSData class]]){
        jsonData = jsonD;
    }else if([jsonD isKindOfClass:[NSDictionary class]]){
        NSDictionary *nonullDict = [self nullDic:jsonD];
        return nonullDict;
    }
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    dic = [self nullDic:dic];
    return dic;
}

+ (NSData *)dataWithDic:(NSDictionary *)dic {
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
    if (![jsonData isKindOfClass:[NSData class]]) {
        return nil;
    }
    return jsonData;
}

+ (NSDictionary *)dicWithData:(NSData *)jsonData {
    if (![jsonData isKindOfClass:[NSData class]] || jsonData.length < 1) {
        return nil;
    }
    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    if (![jsonObj isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    return [NSDictionary dictionaryWithDictionary:(NSDictionary *)jsonObj];
}

//类型识别:将所有的NSNull类型转化成@""
+(id)changeType:(id)myObj
{
    if ([myObj isKindOfClass:[NSDictionary class]])
    {
        return [self nullDic:myObj];
    }
    else if([myObj isKindOfClass:[NSArray class]])
    {
        return [self nullArr:myObj];
    }
    else if([myObj isKindOfClass:[NSString class]])
    {
        return [self stringToString:myObj];
    }
    else if([myObj isKindOfClass:[NSNull class]])
    {
        return [self nullToString];
    }
    else
    {
        return myObj;
    }
}

//将NSDictionary中的Null类型的项目转化成@""
+(NSDictionary *)nullDic:(NSDictionary *)myDic
{
    if ([myDic isKindOfClass:[NSDictionary class]]) {
        NSArray *keyArr = [myDic allKeys];
        NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
        for (int i = 0; i < keyArr.count; i ++)
        {
            id obj = [myDic objectForKey:keyArr[i]];
            obj = [self changeType:obj];
            [resDic setObject:obj forKey:keyArr[i]];
        }
        return resDic;
    }else {
        return @{};
    }
    
}
//将NSDictionary中的Null类型的项目转化成@""
+(NSArray *)nullArr:(NSArray *)myArr
{
    if ([myArr isKindOfClass:[NSArray class]]) {
        NSMutableArray *resArr = [[NSMutableArray alloc] init];
        for (int i = 0; i < myArr.count; i ++)
        {
            id obj = myArr[i];
            obj = [self changeType:obj];
            [resArr addObject:obj];
        }
        return resArr;
    }else {
        return @[];
    }
    
}
//将NSString类型的原路返回
//过滤掉诡异的"null"和"(null)"字符串
+(NSString *)stringToString:(NSString *)string
{
    if ([string isEqualToString:@"null"] || [string isEqualToString:@"(null)"]) {
        return @"";
    }else{
        return string;
    }
}
//将Null类型的项目转化成@""
+(NSString *)nullToString
{
    return @"";
}

+ (BOOL)stringContainsEmoji:(NSString *)string {
    // 过滤所有表情。returnValue为NO表示不含有表情，YES表示含有表情
    __block BOOL containsEmoji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        
        if (0xd800 <= hs &&
            hs <= 0xdbff)
        {
            if (substring.length > 1)
            {
                const unichar ls = [substring characterAtIndex:1];
                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc &&
                    uc <= 0x1f9c0)
                {
                    containsEmoji = YES;
                }
            }
        }
        else if (substring.length > 1)
        {
            const unichar ls = [substring characterAtIndex:1];
            if (ls == 0x20e3 ||
                ls == 0xfe0f ||
                ls == 0xd83c)
            {
                containsEmoji = YES;
            }
        }
        else
        {
            // non surrogate
            if (0x2100 <= hs &&
                hs <= 0x27ff)
            {
                containsEmoji = YES;
            }
            else if (0x2B05 <= hs &&
                     hs <= 0x2b07)
            {
                containsEmoji = YES;
            }
            else if (0x2934 <= hs &&
                     hs <= 0x2935)
            {
                containsEmoji = YES;
            }
            else if (0x3297 <= hs &&
                     hs <= 0x3299)
            {
                containsEmoji = YES;
            }
            else if (hs == 0xa9 ||
                     hs == 0xae ||
                     hs == 0x303d ||
                     hs == 0x3030 ||
                     hs == 0x2b55 ||
                     hs == 0x2b1c ||
                     hs == 0x2b1b ||
                     hs == 0x2b50)
            {
                containsEmoji = YES;
            }
        }
        
        if (containsEmoji)
        {
            *stop = YES;
        }
    }];
    return containsEmoji;
}

#pragma mark 音频文件播放
+ (void)playSoundWithFileName:(NSString *)name fileType:(NSString *)type {
        //name是音频文件的名称
//        NSString *urlString = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] pathForResource:name ofType:type]];
        SystemSoundID soundID = 0;

        NSURL *url = [NSURL URLWithString:name];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)url, &soundID);

        AudioServicesPlaySystemSound(soundID);
}


+ (NSString *) utf8ToUnicode:(NSString *)string{
    
    NSUInteger length = [string length];
    NSMutableString *str = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++){
        NSMutableString *s = [NSMutableString stringWithCapacity:0];
        unichar _char = [string characterAtIndex:i];
        // 判断是否为英文和数字
        if (_char <= '9' && _char >='0'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='a' && _char <= 'z'){
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else if(_char >='A' && _char <= 'Z')
        {
            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]];
        }else{
            // 中文和字符
            [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
            // 不足位数补0 否则解码不成功
            if(s.length == 4) {
                [s insertString:@"00" atIndex:2];
            } else if (s.length == 5) {
                [s insertString:@"0" atIndex:2];
            }
        }
        [str appendFormat:@"%@", s];
    }
    return str;
}

+ (BOOL)checkOnceADayWithKey:(NSString *)key {
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDate *now = [NSDate date];
    NSDate *agoDate = [userDefault objectForKey:key];
        
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
    NSString *ageDateString = [dateFormatter stringFromDate:agoDate];
    NSString *nowDateString = [dateFormatter stringFromDate:now];
        
    if ([ageDateString isEqualToString:nowDateString]) {
        
        return NO;
     }else{
         
         [userDefault setValue:now forKey:key];
         [userDefault synchronize];
         return YES;
     }
}


+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形：
+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

+ (BOOL)inputShouldNumber:(NSString *)inputString {
    if (inputString.length == 0)
        return NO;
        NSString *regex = @"^(-)?[1-9][0-9]*$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        return [pred evaluateWithObject:inputString];
}


+ (CGFloat)heightOfString:(NSString *)str font:(UIFont *)font width:(CGFloat)w maxHeight:(CGFloat)height{
    if (str.length == 0 || w <= 0 || height < 20) {
        return 0;
    }
    if (!font) {
        font = [UIFont systemFontOfSize:14];
    }
    CGSize size = [str boundingRectWithSize:CGSizeMake(w, 99999999)
                                    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                 attributes:@{NSFontAttributeName: font}
                                    context:nil].size;
    CGFloat h = size.height;
    return MIN(h, height);
}

// 是否为邮箱地址
+ (BOOL)isEmailType {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}
//去除字符串的空格
+ (NSString *) GetRidOfBlankSpace:(NSString *) value
{
    NSString *temp = [value stringByReplacingOccurrencesOfString:@" " withString:@""];
    return temp;
}

+ (NSString *)appendUrl:(NSString *)url WithValue:(NSString *)value key:(NSString *)key{
    
    NSMutableString *string = [[NSMutableString alloc]initWithString:url];
    @try {
        NSRange range = [string rangeOfString:@"?"];
        if (range.location != NSNotFound) {//找到了
            //如果?是最后一个直接拼接参数
            if (string.length == (range.location + range.length)) {
                NSLog(@"最后一个是?");
                string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
            }else{//如果不是最后一个需要加&
                if([string hasSuffix:@"&"]){//如果最后一个是&,直接拼接
                    string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
                }else{//如果最后不是&,需要加&后拼接
                    string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,value]];
                }
            }
        }else{//没找到
            if([string hasSuffix:@"&"]){//如果最后一个是&,去掉&后拼接
                string = (NSMutableString *)[string substringToIndex:string.length-1];
            }
            string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"?%@=%@",key,value]];
        }
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    
    return string.copy;
}

+ (NSString *)stringToUnicode:(NSString *)str {
    
    NSString *codeStr = @"";
    if ([str isKindOfClass:[NSString class]] && str.length > 0 ) {
        NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
        NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
        codeStr = [str stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    }
    return codeStr;
}

//大写转小写
+ (NSString *)stringToLower:(NSString *)str {
     for (int i = 0; i < str.length; i++) {
         if([str characterAtIndex:i] >='A' &  [str characterAtIndex:i] <='Z') {
             char temp = [str characterAtIndex:i] +32;
             NSRange range =NSMakeRange(i,1);
             str = [str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
         }
     }
     return str;
}



+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [Utilities _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [Utilities _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}


#pragma mark 生成image
+ (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size {
    //下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    return theImage;
}

+ (UIImage *)currentViewToImage {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return capturedScreen;
}

//获取当前主窗口
+ (UIViewController *)getCurrentVC {
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    return result;
}

+ (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSString *)encodStr {

    NSString * urlStr=[encodStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return urlStr;
}

+ (BOOL)getIsIpad {
    NSString *deviceType = [UIDevice currentDevice].model;
        if([deviceType isEqualToString:@"iPhone"]) {
        //iPhone
        return NO;
    }
    else if([deviceType isEqualToString:@"iPod touch"]) {
        //iPod Touch
        return NO;
    }
    else if([deviceType isEqualToString:@"iPad"]) {
        //iPad
        return YES;
    }
    return NO;
}

@end
